#include "NameList.h"

NameList::NameList()
{
    list.open("nameList", ios_base::in);
    if(list.fail())
    {
        cout << "Erreur!!"<< endl;
    }
     list.seekg(ios_base::beg);
}

NameList::~NameList()
{
     list.close();
}

void NameList::searchName(string code, string& name, string& surname)
{
    list.seekg(ios_base::beg);
    string s= "";
    string num;
    int numPerso = code[1] - '0';

    int i = 1;
    bool peek = false;
    if(isCode(code))
    {
        while(!isEnd() and !peek)
        {
            peek = i == numPerso;
            getline(list, num);
            getline(list, s);
            i++;
        }
    }
    if(i==numPerso+1)
    {
        surname = readWord(s);
        name = readWord(s);
    }

}

bool NameList::isEnd()
{
    bool end = list.peek()==EOF;
    if(list.eof())
    {
        list.clear();
    }
    return end;

}

bool NameList::isCode(string n)
{
    return n[0]=='%';
}

 string NameList::readWord(string& s)
{
    int i = 0;
    char c = s[i];
    string word = "";
    while(c != ' ' and c != '\0')
    {
        word += c;
        i++;
        c = s[i];
    }
    s.erase(0, i+1);
    return word;
}


